import { onMounted, reactive, ref, watch, onUnmounted } from 'vue';
import { errorHandling } from '@/api/error-handling';
import Worker from '@/hooks/worker/nibp-worker.js?worker'; //
export const useScatterChart = (option, props, key1, key2) => {
    const commonChartRef = ref();
    const state = reactive({
        tableData: []
    });
    let oldId = undefined;
    const highlightItem = (index) => {
        commonChartRef.value.dispatchAction({
            type: 'downplay',
            dataIndex: oldId
        });
        commonChartRef.value.dispatchAction({
            type: 'highlight',
            dataIndex: index
        });
        oldId = index;
    };
    onMounted(() => {
        commonChartRef.value?.setOption(option);
    });
    const worker = new Worker(); // 开启副线程
    let start;
    const pageLoading = ref(false);
    const getChartData = async () => {
        pageLoading.value = true;
        await errorHandling(props.config.historyApi, { deviceId: props.deviceId }, res => {
            // state.tableData = res.data
            start = (new Date()).getTime();
            worker.postMessage({
                data: res.data,
                key1,
                key2
            });
        });
        pageLoading.value = false;
    };
    watch(() => props.visible, () => {
        if (!props.visible) {
            commonChartRef.value.dispatchAction({
                type: 'downplay',
                dataIndex: oldId
            });
        }
        else {
            getChartData();
        }
    }, {
        immediate: true
    });
    let chartData = [];
    const setOption = () => {
        commonChartRef.value?.setOption({
            series: [
                {
                    data: chartData
                }
            ]
        });
    };
    worker.onmessage = e => {
        chartData = e.data.chartData;
        state.tableData = e.data.tableData;
        // console.log(state.tableData)
        setOption();
        console.log((new Date()).getTime() - start);
    };
    const rowClick = (row) => {
        state.tableData.forEach(item => {
            if (item.id === row.id) {
                item.is_active = true;
            }
            else {
                item.is_active = false;
            }
        });
        highlightItem(row.id);
    };
    onUnmounted(() => {
        worker.terminate();
    });
    return {
        commonChartRef,
        rowClick,
        state,
        pageLoading
    };
};
